/*
tcp client with reconnect
E-Mail : Mike_Zhang@live.com
*/

package main

import (
    "net"
    "fmt"
    "time"
    "os"
)

func doTask(conn net.Conn) {
	var buf [1460]byte
	sendch := make(chan []byte)
    defer close(sendch)
    go doSend(sendch)
    sendch <- str_test[0:]
    for {
	    n, err := conn.Read(buf[0:])
	    if err != nil {
	    	fmt.Println("rec goroutine close")
	 		//closeSocketCh(ch)
			return
	    }
	    fmt.Println("Reply form server", string(buf[0:n]))
    }
}

func doSend(ch <-chan []byte) {
    // Using for-range to exit goroutine
    // range has the ability to detect the close/end of a channel
    for x := range ch {
        fmt.Println("send ", x)
    }
    fmt.Println("send goroutine close")
}
var str_test = []byte{0x02, 0x00, 0x0e, 0x51, 0x01 ,0x08, 0x01, 0x01, 0x02, 0x15, 0x08, 0x05, 0x50, 0x10, 0x01, 0x1a, 0x23}
    
func main() {
	service := "192.168.251.170:50002"
	addr, err := net.ResolveTCPAddr("tcp4", service)
    //hostInfo := "192.168.251.170.:50002"
	 if err != nil {
        fmt.Fprintf(os.Stderr, "Fatal2 error: %s", err.Error())
        os.Exit(1)
    }

    for {
        conn,err := net.DialTCP("tcp", nil, addr)
        fmt.Print("connect (",service)
        if err != nil {
            fmt.Println(") fail")
        }else{
            fmt.Println(") ok")
            defer conn.Close()
            doTask(conn)
        }
        time.Sleep(2 * time.Second)
    }
}



